package com.xiaoc.bulldozer.common.util;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

import com.xc.framework.common.utils.DateUtil;

/**
 * 订单工具类
 *
 * @author mayong
 *
 * @date Mar 18, 2016
 *
 */
public class TradeUtil {

    private static final int FILL_LENGTH = 8;

    /**
     * 生成订单号
     *
     * 订单类型 2位<br/>
     * 当前时间戳 12位<br/>
     * code 最大7位<br/>
     * 随机数 8位<br/>
     * 
     * @return
     */
    public static String generateTradeNo(String tradeType, String sign) {

        String code = sign.length() >= FILL_LENGTH ? sign : fillZero(sign, FILL_LENGTH, "0");

        String dateStr = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");

        String randomStr = generateString(8);

        return tradeType + dateStr + code + randomStr;
    }

    /**
     * 返回一个定长的随机字符串(只包含数字)
     * 
     * @param length
     *            随机字符串长度
     * @return 随机字符串
     */
    private static String generateString(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 分 转换为 元
     * 
     * @param fen
     * @return
     */
    public static BigDecimal convertFenToYuan(Integer fen, Integer scale) {

        BigDecimal divisor = new BigDecimal(100);
        BigDecimal dividend = new BigDecimal(fen);
        return dividend.divide(divisor, scale, BigDecimal.ROUND_HALF_UP);
    }

    /*
     * 数字不足位数左补0
     * 
     * @param str
     * 
     * @param strLength
     */
    public static String fillZero(String str, int length, String fillChar) {
        int strLen = str.length();
        if (strLen < length) {
            while (strLen < length) {
                StringBuffer sb = new StringBuffer();
                sb.append(fillChar).append(str);
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(generateTradeNo("10", "10"));
    }
}
